package visiopuce.ui;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import visiopuce.objets.Alteration;
import visiopuce.objets.Bande;
import visiopuce.objets.Champ;
import visiopuce.objets.VerifBiomol;
import visiopuce.objets.VerifFish;
import visiopuce.service.AlterationServiceImpl;
import visiopuce.service.PrelevementServiceImpl;
import visiopuce.service.ReferentielServiceImpl;
import visiopuce.service.ResultatServiceImpl;

public class CompteRenduDialog extends Dialog {

	private int idPuce;
	private int idResultat;
	private Text tConclusion;
	private HashMap<Integer, Text> tCNVInt = new HashMap<Integer, Text>();
	private HashMap<Integer, Text> tGene = new HashMap<Integer, Text>();
	private HashMap<Integer, Text> tVerifFish = new HashMap<Integer, Text>();
	private HashMap<Integer, Text> tTransmissionFish = new HashMap<Integer, Text>();
	private HashMap<Integer, Text> tVerifBM = new HashMap<Integer, Text>();
	private HashMap<Integer, Text> tTransmissionBM = new HashMap<Integer, Text>();

	public CompteRenduDialog(Shell parentShell, int idPuce, int idResultat) {
		super(parentShell);
		this.idPuce = idPuce;
		this.idResultat = idResultat;
		setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.APPLICATION_MODAL);
		setBlockOnOpen(true);
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Compte rendu de la puce");
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite dialogArea = (Composite) super.createDialogArea(parent);
		dialogArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		dialogArea.setLayout(new GridLayout());

		ScrolledComposite scrolled = new ScrolledComposite(dialogArea, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		scrolled.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		scrolled.setLayout(new GridLayout());
		scrolled.setExpandVertical(true);
		scrolled.setExpandHorizontal(true);

		Composite composite = new Composite(scrolled, SWT.NONE);
		scrolled.setContent(composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		composite.setLayout(new GridLayout(1, false));

		List<Alteration> alterations = AlterationServiceImpl.getInstance().getAlterationAVerif(idPuce);
		if (alterations.size() > 0) {
			Group groupeVerif = new Group(composite, SWT.BORDER);
			groupeVerif.setLayout(new GridLayout(alterations.size(), false));
			groupeVerif.setText("CNV vérifiés");
			for (Alteration alteration : alterations) {
				Group groupeAlt = new Group(groupeVerif, SWT.BORDER);
				groupeAlt.setLayout(new GridLayout(2, false));
				groupeAlt.setText("CNV : " + alteration.getChromosome() + ":" + alteration.getDebutHg19() + "-" + alteration.getChromosome() + ":" + alteration.getDebutHg19());

				Label lbCNVInt = new Label(groupeAlt, SWT.BORDER);
				lbCNVInt.setText("CNV d'intérêt :");

				tCNVInt.put(alteration.getIdAlteration(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));

				Champ champCNVInt = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("cnvInteret", "Alt-" + alteration.getIdAlteration());
				if (champCNVInt != null) {
					tCNVInt.get(alteration.getIdAlteration()).setText(champCNVInt.getValeur());
				} else {
					String txt = "";
					if (alteration.getNbCopie() > 2) {
						txt = "Duplication ";
					} else {
						txt = "Délétion ";
					}
					String bandesChr = "";
					List<Bande> bandes = ReferentielServiceImpl.getInstance().getBandesByCNV(alteration);
					for (Bande bande : bandes) {
						bandesChr += bande.getLibelle();
					}
					NumberFormat formatter = NumberFormat.getInstance();
					double taille = Math.round((alteration.getFinHg19() - alteration.getDebutHg19()) / 1000);
					txt += "interstitielle d'environ " + taille + " kb de la région chromosomique " + alteration.getChromosome() + bandesChr + " entre les marqueurs " + alteration.getSondeDebut().trim() + " (" + formatter.format(alteration.getDebutHg19()) + " pb) et "
							+ alteration.getSondeFin().trim() + " (" + formatter.format(alteration.getFinHg19()) + " pb).";
					tCNVInt.get(alteration.getIdAlteration()).setText(txt);
				}
				GridData gd_tCNVInt = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
				gd_tCNVInt.widthHint = 300;
				gd_tCNVInt.heightHint = 100;
				tCNVInt.get(alteration.getIdAlteration()).setLayoutData(gd_tCNVInt);

				Label lblGenes = new Label(groupeAlt, SWT.BORDER);
				lblGenes.setText("Gênes d'intérêt");

				tGene.put(alteration.getIdAlteration(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));
				Champ champGeneInteret = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("geneInteret", "Alt-" + alteration.getIdAlteration());
				if (champGeneInteret != null) {
					tGene.get(alteration.getIdAlteration()).setText(champGeneInteret.getValeur());
				} else {
					if (alteration.getPrecisionVerif() != null) {
						tGene.get(alteration.getIdAlteration()).setText(alteration.getPrecisionVerif());
					}
				}
				GridData gd_tGene = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
				gd_tGene.widthHint = 300;
				gd_tGene.heightHint = 100;
				tGene.get(alteration.getIdAlteration()).setLayoutData(gd_tGene);

				List<VerifFish> verifFishs = ResultatServiceImpl.getInstance().getVerifFishByIdAlteration(alteration.getIdAlteration());
				for (VerifFish verifFish : verifFishs) {
					Label lblVerif = new Label(groupeAlt, SWT.BORDER);
					lblVerif.setText("Vérification FISH: ");
					tVerifFish.put(verifFish.getIdVerifFish(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));
					Champ champconfF = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("confirmeFish", "Fish-" + verifFish.getIdVerifFish());
					if (champconfF != null) {
						tVerifFish.get(verifFish.getIdVerifFish()).setText(champconfF.getValeur());
					} else {
						if (verifFish.getDetecte()) {
							tVerifFish.get(verifFish.getIdVerifFish()).setText("Confirmé par FISH.");
						} else {
							tVerifFish.get(verifFish.getIdVerifFish()).setText("Non confirmé par FISH.");
						}
					}
					GridData gd_tVerifFish = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gd_tVerifFish.widthHint = 300;
					gd_tVerifFish.heightHint = 100;
					tVerifFish.get(verifFish.getIdVerifFish()).setLayoutData(gd_tVerifFish);

					Label lblTransmission = new Label(groupeAlt, SWT.BORDER);
					lblTransmission.setText("Transmission : ");
					tTransmissionFish.put(verifFish.getIdVerifFish(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));
					Champ champtransF = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("transmissionFish", "Fish-" + verifFish.getIdVerifFish());
					if (champtransF != null) {
						tTransmissionFish.get(verifFish.getIdVerifFish()).setText(champtransF.getValeur());
					} else {
						if (verifFish.getHerite() != null) {
							tTransmissionFish.get(verifFish.getIdVerifFish()).setText(verifFish.getHerite());
						}
					}
					GridData gd_tTransmissionFish = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gd_tTransmissionFish.widthHint = 300;
					gd_tTransmissionFish.heightHint = 100;
					tTransmissionFish.get(verifFish.getIdVerifFish()).setLayoutData(gd_tTransmissionFish);
				}

				List<VerifBiomol> verifBMs = ResultatServiceImpl.getInstance().getVerifBiomolByIdAlteration(alteration.getIdAlteration());
				for (VerifBiomol verifBM : verifBMs) {

					Label lblVerif = new Label(groupeAlt, SWT.BORDER);
					lblVerif.setText("Vérification qPCR: ");
					tVerifBM.put(verifBM.getIdVerifBioMol(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));
					Champ champconfirmeBM = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("confirmeBM", "BM-" + verifBM.getIdVerifBioMol());

					if (champconfirmeBM != null) {
						tVerifBM.get(verifBM.getIdVerifBioMol()).setText(champconfirmeBM.getValeur());
					} else {
						if (verifBM.getDetecte() != null) {
							if (verifBM.getDetecte() == 1) {
								tVerifBM.get(verifBM.getIdVerifBioMol()).setText("Confirmé par qPCR");
							} else if (verifBM.getDetecte() == 0) {
								tVerifBM.get(verifBM.getIdVerifBioMol()).setText("Non confirmé par qPCR");
							} else if (verifBM.getDetecte() == 2) {
								tVerifBM.get(verifBM.getIdVerifBioMol()).setText("Ininterprétable par qPCR");
							}
						} else {
							tVerifBM.get(verifBM.getIdVerifBioMol()).setText("qPCR non encre réalisée");
						}
					}
					GridData gd_tVerifBM = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gd_tVerifBM.widthHint = 300;
					gd_tVerifBM.heightHint = 100;
					tVerifBM.get(verifBM.getIdVerifBioMol()).setLayoutData(gd_tVerifBM);

					Label lblTransmission = new Label(groupeAlt, SWT.BORDER);
					lblTransmission.setText("Transmission : ");
					tTransmissionBM.put(verifBM.getIdVerifBioMol(), new Text(groupeAlt, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL));
					Champ champTransmissionBM = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("transmissionBM", "BM-" + verifBM.getIdVerifBioMol());
					if (champTransmissionBM != null) {
						tTransmissionBM.get(verifBM.getIdVerifBioMol()).setText(champTransmissionBM.getValeur());
					} else {
						if (verifBM.getHerite() != null) {
							tTransmissionBM.get(verifBM.getIdVerifBioMol()).setText(verifBM.getHerite());
						}
					}
					GridData gd_tTransmissionBM = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gd_tTransmissionBM.widthHint = 300;
					gd_tTransmissionBM.heightHint = 100;
					tTransmissionBM.get(verifBM.getIdVerifBioMol()).setLayoutData(gd_tTransmissionBM);
				}

			}
		}

		Label lblConclusion = new Label(composite, SWT.BORDER);
		lblConclusion.setText("Conclusion");
		tConclusion = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
		GridData gd_tConclusion = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_tConclusion.widthHint = 400;
		gd_tConclusion.heightHint = 100;
		tConclusion.setLayoutData(gd_tConclusion);

		Champ champccl = PrelevementServiceImpl.getInstance().getChampByTypeAndIdObjet("conclCptRendu", "Res-" + idResultat);
		if (champccl == null || (champccl != null && (champccl.getValeur() == null || champccl.getValeur().isEmpty()))) {
			tConclusion.setText("Dans ce contexte, un prélèvement de sang sur héparine et EDTA des parents est nécessaire pour rechercher le caractère de novo ou hérité des ces remaniements. Une consultation en génétique est souhaitable.");
		} else {
			tConclusion.setText(champccl.getValeur());
		}

		composite.setSize(composite.computeSize(SWT.NONE, SWT.NONE, true));
		scrolled.setVisible(true);

		return dialogArea;
	}

	// override method to use "Login" as label for the OK button
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		// if
		// (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(),
		// "cotation")) {
		Button button = createButton(parent, IDialogConstants.OK_ID, "Enregistrer", true);
		button.setText("Enregistrer");
		// }
		createButton(parent, IDialogConstants.CANCEL_ID, "Annuler", false);
	}

	@Override
	protected Point getInitialSize() {
		return new Point(1108, 805);
	}

	@Override
	protected void okPressed() {

		Champ champccl = new Champ();
		champccl.setIdObjet("Res-" + idResultat);
		champccl.setType("conclCptRendu");
		champccl.setValeur(tConclusion.getText());
		ResultatServiceImpl.getInstance().save(champccl);

		for (Entry<Integer, Text> entry : tCNVInt.entrySet()) {
			Integer key = entry.getKey();
			Text txtCNVInt = entry.getValue();
			Champ champCNVInt = new Champ();

			champCNVInt.setIdObjet("Alt-" + key);
			champCNVInt.setType("cnvInteret");
			champCNVInt.setValeur(txtCNVInt.getText());
			ResultatServiceImpl.getInstance().save(champCNVInt);

		}

		for (Entry<Integer, Text> entry : tGene.entrySet()) {
			Integer key = entry.getKey();
			Text txtGene = entry.getValue();
			Champ champGene = new Champ();

			champGene.setIdObjet("Alt-" + key);
			champGene.setType("geneInteret");
			champGene.setValeur(txtGene.getText());
			ResultatServiceImpl.getInstance().save(champGene);

		}
		for (Entry<Integer, Text> entry : tVerifFish.entrySet()) {
			Integer key = entry.getKey();
			Text txtVerifFish = entry.getValue();
			Champ champvf = new Champ();

			champvf.setIdObjet("Fish-" + key);
			champvf.setType("confirmeFish");
			champvf.setValeur(txtVerifFish.getText());
			ResultatServiceImpl.getInstance().save(champvf);

		}
		for (Entry<Integer, Text> entry : tTransmissionFish.entrySet()) {
			Integer key = entry.getKey();
			Text txtTransmissionFish = entry.getValue();
			Champ champtf = new Champ();

			champtf.setIdObjet("Fish-" + key);
			champtf.setType("transmissionFish");
			champtf.setValeur(txtTransmissionFish.getText());
			ResultatServiceImpl.getInstance().save(champtf);

		}
		for (Entry<Integer, Text> entry : tVerifBM.entrySet()) {
			Integer key = entry.getKey();
			Text txtVerifBM = entry.getValue();
			Champ champvbm = new Champ();

			champvbm.setIdObjet("BM-" + key);
			champvbm.setType("confirmeBM");
			champvbm.setValeur(txtVerifBM.getText());
			ResultatServiceImpl.getInstance().save(champvbm);

		}
		for (Entry<Integer, Text> entry : tTransmissionBM.entrySet()) {
			Integer key = entry.getKey();
			Text txttransBM = entry.getValue();
			Champ champtbm = new Champ();

			champtbm.setIdObjet("BM-" + key);
			champtbm.setType("transmissionBM");
			champtbm.setValeur(txttransBM.getText());
			ResultatServiceImpl.getInstance().save(champtbm);

		}

		super.okPressed();
	}

	@Override
	protected void cancelPressed() {
		if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirmation", "Toutes les modifications apportées au compte rendu ne seront pas sauvegardées. Etes-vous certain de vouloir quitter?")) {
			super.cancelPressed();
		}

	}

}
